package com.iot.ht.controller.htpage.service;

import com.iot.core.data.BasePageDtQto;
import com.iot.core.data.BaseQto;
import com.iot.core.data.entity.HtPage;
import com.iot.core.data.entity.HtPageAuth;
import com.iot.core.data.mapper.*;
import com.iot.core.data.service.ServiceImpl;
import com.iot.core.exception.MyException;
import com.iot.core.manager.id.HtIdManager;
import com.iot.core.util.StreamUtil;
import com.iot.ht.controller.htpage.data.HtPageAuthDto;
import com.iot.ht.controller.htpage.data.HtPageDto;
import com.mybatisflex.core.paginate.Page;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.stream.Collectors;

import static com.iot.core.data.entity.table.HtActionTableDef.HT_ACTION;
import static com.iot.core.data.entity.table.HtPageAuthTableDef.HT_PAGE_AUTH;
import static com.iot.core.data.entity.table.HtPageTableDef.HT_PAGE;
import static com.iot.core.data.entity.table.HtUserTableDef.HT_USER;

@Slf4j
@Service
public class HtPageService extends ServiceImpl<HtPageMapper, HtPage> implements IHtPageService {
    @Autowired
    HtDbMapper htdbMapper;
    @Autowired
    HtPageAuthMapper htPageAuthMapper;
    @Autowired
    HtCtlMapper htCtlMapper;
    @Autowired
    HtActionMapper htActionMapper;

    @Override
    public Page<HtPageDto> page(BasePageDtQto qm){
        var qw=getBaseMapper().getQueryWrapper();
        qw.select(HT_PAGE.ALL_COLUMNS)
                .select("b.Name as crtUname")
                .select("c.Name as edtUname")
                .from(HT_PAGE).as("a")
                .innerJoin(HT_USER).as("b")
                .on(" a.crt_uid=b.id" )
                .innerJoin(HT_USER).as("c")
                .on(" a.edt_uid=c.id" )
                ;
                
        if(StringUtils.hasText(qm.getDtb() )){
            qw.and( HT_PAGE.CRT_DT.ge(qm.getDB()));
        }

        if(StringUtils.hasText(qm.getDte() )){
            qw.and( HT_PAGE.CRT_DT.lt(qm.getDE()));
        }

        if(StringUtils.hasText(qm.getKey() )){
            if(StringUtils.hasText(qm.getKey() )){
                qw.and( HT_PAGE.CODE.like(qm.getKey())
                        .or( HT_PAGE.NAME.like(qm.getKey()) )

                );

            }
        }
        var sort=qm.getSort();
        qw.orderBy( sort.toString()  );




        var r =getBaseMapper().pageAs(  qm,qw ,HtPageDto.class);
        return r;
    }

    @Override
    public HtPageDto detail(BaseQto qm){
        var m=getById(qm);
        var mm=new HtPageDto();
        getBaseMapper().entityToDto(m,mm);
        mm.setCrtUname( htdbMapper.getName("htuser",m.getCrtUid() ) );
        mm.setEdtUname( htdbMapper.getName("htuser",m.getEdtUid() ) );

        var qwPageAuth=htPageAuthMapper.getQueryWrapper();
        qwPageAuth.and(HT_PAGE_AUTH.HTPAGE_ID.eq( mm.getId() ) );
        qwPageAuth.orderBy(HT_PAGE_AUTH.SORTNO,true);
        var ldbauth=htPageAuthMapper.selectListByQuery(qwPageAuth);
        for(var mauth:ldbauth){
            var mmauth=new HtPageAuthDto();
            htPageAuthMapper.entityToDto(mauth,mmauth);
            mm.getAuths().add(mmauth);
        }
        return mm;
    }
    @Override
    public HtPageDto insertInit(){
        var mm=new HtPageDto();
        mm.setImgurl("layui-icon-form");
        return mm;
    }
    @Override
    public HtPageAuthDto insertAuthInit(){
        var mm = new HtPageAuthDto();
        return mm;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insert(HtPageDto mm){
        var qwold=getBaseMapper().getQueryWrapper();
        qwold.and(HT_PAGE.CODE.eq( mm.getCode()) );
        var mold=getBaseMapper().selectOneByQuery(qwold);
        if(!ObjectUtils.isEmpty(mold)){
            throw new MyException("数据重复");
        }
        var m = new  HtPage();
        getBaseMapper().dtoToEntity(mm,m);
        m.setId(HtIdManager.getInstance().nextLong());
        for(var masrc: mm.getAuths())
        {
            var madst=new HtPageAuth();
            htPageAuthMapper.dtoToEntity(masrc, madst);
            madst.setHtpageId(m.getId());
            htPageAuthMapper.insert(madst  );
        }
        return insert(m);

    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public   int update(HtPageDto mm){
        var m=getById(mm.getId());
        if(!m.getCode().equals(mm.getCode())){
            var qwold=getBaseMapper().getQueryWrapper();
            qwold.and(HT_PAGE.CODE.eq( mm.getCode()) );
            var mold=getBaseMapper().selectOneByQuery(qwold);
            if(!ObjectUtils.isEmpty(mold)){
                throw new MyException("数据重复");
            }
        }
        getBaseMapper().dtoToEntity(mm,m);

        var qwPageAuth=htPageAuthMapper.getQueryWrapper();
        qwPageAuth.and( HT_PAGE_AUTH.HTPAGE_ID.eq( mm.getId() ) );
        qwPageAuth.orderBy(HT_PAGE_AUTH.SORTNO,true);
        var ldbauth=htPageAuthMapper.selectListByQuery(qwPageAuth);
        for(var masrc:mm.getAuths()){
            var madst = StreamUtil.get(ldbauth, a->a.getId().equals(masrc.getId()));

            if (ObjectUtils.isEmpty(madst))
            {
                madst=new HtPageAuth();
                htPageAuthMapper.dtoToEntity(masrc, madst);
                madst.setHtpageId(m.getId());
                htPageAuthMapper.insert(madst );
            }
            else
            {
                htPageAuthMapper.dtoToEntity(masrc, madst);
                htPageAuthMapper.updateById(madst,true);
            }
        }

        for(var madb : ldbauth)
        {
            var masrc= StreamUtil.get(  mm.getAuths(), a->a.getId().equals( madb.getId()) );
            if (masrc == null)
            {
                htPageAuthMapper.deleteById(madb,true);
            }
        }

        return updateById(m);
    }




    public HtPageDto insertInitForCtl(long ctlId){
        var mctl=htCtlMapper.getById(ctlId);
        var qw=htActionMapper.getQueryWrapper();
        qw.and(HT_ACTION.CTL_FULL_NAME.eq( mctl.getCtlFullName() ) )
                .and(HT_ACTION.AUTH_TYPE.eq("Auth"))
                .orderBy(HT_ACTION.ID,true);
        var laction=htActionMapper.selectListByQuery(qw);

        var ename=mctl.getCtlFullName().substring( mctl.getCtlFullName().lastIndexOf(".")+1 ).toLowerCase();
        if(ename.endsWith("controller")){
            ename=ename.substring(0,ename.length()-10 );
        }
        var mm=new HtPageDto();
        mm.setId(htdbMapper.nextLong() );
        mm.setCode("/" + ename + "/index");
        mm.setImgurl("layui-icon-form");
        mm.setLx("后台");
        mm.setName(mctl.getName());
        mm.setMemo(mctl.getMemo());
        var SortNo = 10;
        for(var mact:laction){
            var mauth=new HtPageAuthDto();
            mauth.setId(htdbMapper.nextLong() );
            mauth.setCode(mact.getEname());
            mauth.setName(mact.getName());
            mauth.setMemo(mact.getMemo());
            mauth.setSortno((long) SortNo);
            mauth.setUrls(mact.getFullUrl());
            mm.getAuths().add(mauth);
            SortNo+=10;
        }
        return mm;

    }

}
